package com.lagou.edu.course.remote;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.edu.course.entity.Course;
import com.lagou.edu.course.entity.Lesson;
import com.lagou.edu.course.entity.Section;
import com.lagou.edu.course.mapper.CourseMapper;
import com.lagou.edu.course.mapper.LessonMapper;
import com.lagou.edu.course.mapper.SectionMapper;
import com.lagou.edu.dto.CourseDTO;
import com.lagou.edu.dto.LessonDTO;
import com.lagou.edu.dto.PageResultDTO;
import com.lagou.edu.dto.SectionDTO;
import com.lagou.edu.param.CourseQueryParam;
import com.lagou.edu.remote.CourseRemoteService;
import com.lagou.edu.util.ConvertUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/course")
public class CourseRemoteServiceImpl implements CourseRemoteService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private SectionMapper sectionMapper;
    @Autowired
    private LessonMapper lessonMapper;

    @GetMapping("/getAllCourses")
    @Override
    public List<CourseDTO> getAllCourses(Integer userId) {
        return null;
    }

    @GetMapping("/getPurchasedCourse")
    @Override
    public List<CourseDTO> getPurchasedCourse(Integer userId) {
        return null;
    }

    @GetMapping("/getCourseById")
    @Override
    public CourseDTO getCourseById(@RequestParam("courseId") Integer courseId, @RequestParam(required = false,name = "userId") Integer userId) {
        //如果没有userid 既视为请求为后端请求.
        if (userId == null) {
            var course = courseMapper.selectById(courseId);
            if (course != null) {
                var cond = new Section();

                var dto = ConvertUtil.Convert(course, CourseDTO.class);

                QueryWrapper<Section> queryWrapper = Wrappers.query(cond).eq("course_id", course.getId());
                List<SectionDTO> sectionDTOS = new ArrayList<>();
                var sectionList = sectionMapper.selectList(queryWrapper);
                if (sectionList != null) {
                    sectionList.stream().forEach(item -> {
                        var lessonList = lessonMapper.selectList(Wrappers.query(new Lesson()).eq("course_id", course.getId()).eq("section_id", item.getId()));
                        if (lessonList != null) {
                            var sectionDto = ConvertUtil.Convert(item, SectionDTO.class);
                            sectionDto.setLessonDTOS(ConvertUtil.Convert(lessonList, LessonDTO.class));
                            sectionDTOS.add(sectionDto);
                        }
                    });
                    dto.setSectionDTOS(sectionDTOS);
                }

//                dto.setSectionDTOS(new ArrayList<>());
                return dto;
            }
        } else {
            //ignore web页面请求忽略
        }
        return null;
    }

    @PostMapping(value = "/saveOrUpdateCourse", consumes = "application/json")
    @Override
    public boolean saveOrUpdateCourse(@RequestBody CourseDTO courseDTO) {

        Course course = ConvertUtil.Convert(courseDTO, Course.class);
        try {
            if (course.getId() != null && courseMapper.selectById(course.getId()) != null) {
                int index = courseMapper.updateById(course);
            } else {
                courseMapper.insert(course);
            }
            if (courseDTO.getSectionDTOS() != null) {
                List<SectionDTO> sectionDTOList = courseDTO.getSectionDTOS();
                sectionDTOList.forEach(sectionDTO -> {
                    Section section = ConvertUtil.Convert(sectionDTO, Section.class);
                    section.setCourseId(course.getId());
                    if (section.getId() != null) {
                        sectionMapper.updateById(section);
                    } else {
                        sectionMapper.insert(section);
                    }

                    if (sectionDTO.getLessonDTOS() != null) {
                        var lessonList = sectionDTO.getLessonDTOS();
                        lessonList.forEach(lessonDTO -> {
                            Lesson lesson = ConvertUtil.Convert(lessonDTO, Lesson.class);
                            lesson.setCourseId(course.getId());
                            lesson.setSectionId(section.getId());
                            if (lesson.getId() == null) {
                                lessonMapper.insert(lesson);
                            } else {
                                lessonMapper.updateById(lesson);
                            }
                        });
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @PostMapping(value = "/getQueryCourses", consumes = "application/json")
    @Override
    public PageResultDTO<CourseDTO> getQueryCourses(@RequestBody CourseQueryParam courseQueryParam) {
        PageResultDTO<CourseDTO> resultDTO = new PageResultDTO<>();
        String courseName = courseQueryParam.getCourseName();
        Integer status = courseQueryParam.getStatus();
        Page<Course> page = new Page<>(courseQueryParam.getCurrentPage(), courseQueryParam.getPageSize());
        QueryWrapper<Course> queryWrapper = Wrappers.query(new Course());
        if (StringUtils.isNotEmpty(courseName)) {
            queryWrapper.like("course_name", courseName);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        Page<Course> records = courseMapper.selectPage(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(records.getRecords())) {
            resultDTO.setRecords(ConvertUtil.Convert(records.getRecords(), CourseDTO.class));
            resultDTO.setTotal(records.getTotal());
            resultDTO.setCurrent(courseQueryParam.getCurrentPage());
            resultDTO.setSize(records.getSize());
            return resultDTO;
        }
        resultDTO.setRecords(new ArrayList<>());
        resultDTO.setCurrent(courseQueryParam.getCurrentPage());
        return resultDTO;
    }
}
